package connexionServer;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class ServeurUDP implements Runnable {
	private static final int TIMEOUT_RECEPTION_REPONSE = 0;
	private DatagramSocket socket = null;
	private byte[] receiveData = new byte[1024];
	private byte[] sendData = new byte[1024];
	private Thread activite = null;
	private int port;

	public ServeurUDP(int port)
	{


		// On essaye de créer notre socket serveur UDP
		this.port = port;
		activite = new Thread(this);
		activite.start();



	}

	@Override
	public void run() {

		try
		{
			//System.out.println("Attente nouvelle demande UDP ....");
			socket = new DatagramSocket(port);
			socket.setSoTimeout(TIMEOUT_RECEPTION_REPONSE);
			DatagramPacket paquetRecu = new DatagramPacket(receiveData, receiveData.length);
			socket.receive(paquetRecu);
			String requete = new String(paquetRecu.getData());
			InetAddress IPAddress = paquetRecu.getAddress();
			int portC = paquetRecu.getPort();
			// Si on reçoit un "ping", on répond "pong" à celui qui nous l'a envoyé
			if (requete.contains("Ping"))
			{
				sendData = "Pong".getBytes();
				DatagramPacket paquetRetour = new DatagramPacket(sendData, sendData.length, IPAddress, portC);
				socket.send(paquetRetour);
				socket.close();
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

}
